<?php
/**
 * Created by PhpStorm.
 * User: iceberg
 * Date: 2018-10-20
 * Time: 1:05
 */

namespace app\service;


use app\model\Category;
use app\model\Goods;
use app\model\Order;
use app\model\Storage;
use app\model\Supplier;
use app\model\Unit;
use app\validate\GoodsValidate;
use app\validate\OrderValidate;
use think\facade\Request;

class OutorderService
{
    //分页列表
    public function page()
    {
        //获取request参数
        $request = Request::get();
        $name = isset($request['name']) ? $request['name'] : '';
        $status = isset($request['status']) ? $request['status'] : -1;
        //封装where查询条件
        $where = [];
        $status == -1   ||  $where[]   = ['status', '=' ,$status];
        empty($name)    ||  $where[]   = ['name', 'like', '%'.$name.'%'];
        //拼接page参数
        $pageParam = ['query' => []];
        $pageParam['query']['status'] = $status;
        $pageParam['query']['name'] = $name;
        if($status == -1 && empty($name)){
            return Order::with('supplier','storage')->where('status', '=', 0)->whereOr('status', '=', 3)->order('id desc')->paginate(10,false,$pageParam);
        }else{
            return Order::with('supplier','storage')->where($where)->order('id desc')->paginate(10,false,$pageParam);
        }

    }

    //统计个数
    public function count()
    {
        //只查0作废3出库
        return Order::where('status', '=', 0)->whereOr('status', '=', 3)->count();
    }

    //获取供应商列表
    public function getSupplier()
    {
        return Supplier::all();
    }

    //获取货物类别
    public function getCategory()
    {
        return Category::all();
    }

    //获取单位
    public function getUnit()
    {
        return Unit::all();
    }

    //获得仓库
    public function getStorage()
    {
        return Storage::all();
    }

    //获得order
    public function getOrder($id)
    {
        return Order::get($id);
    }

    //根据订单号获取货物清单
    public function getGoodsByOrderID($id)
    {
        return Goods::with('category,unit')->where('order_id', '=', $id)->select();
    }

    //保存出库单
    public function save()
    {
        Request::isPost() || die('request not post!');
        //获取参数
        $param = Request::param();
        //订单状态（已出库）
        $param['status'] = 3;
        //验证goods是否有？
        if(!isset($param['category'])){
            return ajax_return(100, '订单中货物不能为空<br/>请取消关闭页面重新添加！');die;
        }

        //----验证出库单
        $outOrder = new Order();
        $outOrder->startTrans();  //开启事务
        $error = $this->_validate($param, 'outorder');
        if(!is_null($error)){
            return ajax_return(100, $error);
        }
        $outOrder->allowField(true)->save($param);
        //货物验证
        foreach ($param['category'] as $k => $v){
            $goods = new Goods();
            $goods->order_id = $outOrder->id;
            $goods->supplier_id = $outOrder->supplier_id;
            $goods->storage_id  = $outOrder->storage_id;
            $goods->customer_id = $outOrder->customer_id;
            $goods->category_id = $param['category'][$k];
            //$goods->price = $param['price'][$k];
            $goods->num = $param['num'][$k];
            $goods->unit_id = $param['unit'][$k];
            $errorGoods = $this->_goodsValidate($goods);
            if(!is_null($errorGoods)){
                //回滚事务
                $outOrder->rollback();
                return ajax_return(100, $errorGoods);die;
            }
        }
        //货物数组
        $goodsAll = [];
        $orderPrice = 0;
        foreach ($param['category'] as $k => $v){
            $price = (Category::get($param['category'][$k]))->price;
            $total = $param['num'][$k] * $price;
            $orderPrice += $total;
            $g = [
                'order_id'      =>  $outOrder->id,
                'supplier_id'   =>  $outOrder->supplier_id,
                'storage_id'    =>  $outOrder->storage_id,
                'customer_id'   =>  $outOrder->customer_id,
                'category_id'   =>  $param['category'][$k],
                'price'         =>  $price,
                'num'           =>  $param['num'][$k],
                'unit_id'       =>  $param['unit'][$k],
                'status'        =>  3,
                'total'         =>  $total,
            ];
            $goodsAll[] = $g;
        }
        //货物批量添加
        $goods = new Goods();
        //开启事务
        $goods->startTrans();
        if(!$goods->saveAll($goodsAll)){
            $goods->rollback();
            $outOrder->rollback();
            return ajax_return(100, '保存失败');die;
        }

        //----计算出订单总价更新数据库
        $outOrder->total = $orderPrice;
        if(!$outOrder->save()){
            //回滚事务
            $outOrder->rollback();
            $goods->rollback();
            return ajax_return(100, '保存失败');
        }


        //提交事务
        $goods->commit();
        $outOrder->commit();
        return ajax_return(0, '保存成功');


    }

    //更新订单
    public function update()
    {
        Request::isPost() || die('request not post!');
        //------订单的值更新
        //获取参数
        $param = Request::param();
        //订单状态（已经出库）
        $param['status'] = 3;
        //是否通过验证
        $error = $this->_validate($param);
        if(!is_null($error)) {
            return ajax_return(100,$error);
        }
        //dump($param);die;
        //更新订单
        $order = Order::get($param['id']);
        $order->startTrans();  //开启事务
        $order->name        =   $param['name'];
        $order->author      =   $param['author'];
        $order->supplier_id =   $param['supplier_id'];
        $order->storage_id  =   $param['storage_id'];
        $order->customer_id =   $param['customer_id'];
        $order->status      =   3;  //订单状态（已经出库）
        $order->desc        =   $param['desc'];
        $order->save();

        //------货物原来的删除
        Goods::startTrans();
        if(!Goods::where('order_id', '=' ,$param['id'])->delete())
        {
            $order->rollback();
            Goods::rollback();
            return ajax_return(100, '删除失败');
        }

        //------货物重新添加
        //货物验证
        foreach ($param['category'] as $k => $v){
            $goods = new Goods();
            $goods->order_id = $param['id'];
            $goods->supplier_id = $param['supplier_id'];
            $goods->storage_id  = $param['storage_id'];
            $goods->category_id = $param['category'][$k];
            $goods->customer_id = $param['customer_id'];
            $goods->num = $param['num'][$k];
            $goods->unit_id = $param['unit'][$k];
            $errorGoods = $this->_goodsValidate($goods);
            if(!is_null($errorGoods)){
                //回滚事务
                $order->rollback();
                Goods::rollback();
                return ajax_return(100, $errorGoods);
            }
        }
        //货物数组
        $goodsAll = [];
        $orderPrice = 0;  //订单总价
        foreach ($param['category'] as $k => $v){
            $price = (Category::get($param['category'][$k]))->price;
            $total = $price * $param['num'][$k];
            $orderPrice += $total;
            $g = [
                'order_id'      =>  $param['id'],
                'supplier_id'   =>  $param['supplier_id'],
                'storage_id'    =>  $param['storage_id'],
                'category_id'   =>  $param['category'][$k],
                'customer_id'   =>  $param['customer_id'],
                'price'         =>  $price,
                'num'           =>  $param['num'][$k],
                'unit_id'       =>  $param['unit'][$k],
                'status'        =>  3,  //  已经出库
                'total'         =>  $total,
            ];
            $goodsAll[] = $g;
        }
        //----货物批量添加
        $goods = new Goods();
        if(!$goods->saveAll($goodsAll))
        {
            //回滚事务
            $order->rollback();
            Goods::rollback();
            return ajax_return(100, '批量添加货物失败');
        }

        //----计算出订单总价更新数据库
        if($order->total != $orderPrice){  //不相等才更新
            $order->total = $orderPrice;
            if(!$order->save()){
                //回滚事务
                $order->rollback();
                Goods::rollback();
                return ajax_return(100, '更新出库单总价失败');
            }
        }

        $order->commit();  //订单
        Goods::commit();  //货物
        return ajax_return(0, '操作成功');
    }

    //删除
    public function delete($id)
    {
        Request::isPost() || die('request not post!');
        Goods::startTrans();
        Order::startTrans();
        if(!Goods::where('order_id', '=' ,$id)->delete()) {
            Goods::rollback();
            return ajax_return(100, '删除失败');die;
        }

        if(!Order::destroy($id)){
            Goods::rollback();
            Order::rollback();
            return ajax_return(100, '删除失败');die;
        }

        Goods::commit();
        Order::commit();
        return ajax_return(0, '删除成功');
    }


    //验证器
    private function _validate($data, $scene='')
    {
        //验证
        $validate = new OrderValidate();
        if(!$validate->scene($scene)->check($data))
        {
            return $validate->getError();
        }
    }
    //货物验证器
    private function _goodsValidate($data, $scene='')
    {
        //验证
        $validate = new GoodsValidate();
        if(!$validate->scene($scene)->check($data))
        {
            return $validate->getError();
        }
    }
}
